/*
 * mainMPI.cpp
 *
 *  Created on: Jan 10, 2013
 *      Author: fs
 */

#include <stdlib.h>
#include <mpi.h>
#include "Configuration.h"
#include "CsvLoader.h"
#include "GenCalc.h"
#include "ParallelWorker.h"

using namespace std;

int main(int argc, char* argv[])
{
	int rank;
	int size;

	Configuration* conf = new Configuration();
	conf->parseArgs(argc, argv);

	MPI::Init(argc, argv);
	size = MPI::COMM_WORLD.Get_size();
	rank = MPI::COMM_WORLD.Get_rank();

	CsvLoader* loader = new CsvLoader();
	int result = loader->loadFile(conf->inputFile);

	if(result != EXIT_SUCCESS)
	{
		if(rank == 0)
		{
			cout << "\n Loading failed..." << conf->inputFile;
		}

		MPI_Abort(MPI::COMM_WORLD, MPI_ERR_NO_SUCH_FILE);
	}

	GenCalc* calc = new GenCalc(loader->getData(), conf);

	if (rank == 0)
	{
		long start = time(NULL);
		conf->printUsedParams();
		printf("Pocet procesu MPI... %d\n", size);

		calc->initPopulation();		// prvni populace
		calc->nextEvolution(0, size);

		for (int i = 1; i < conf->generationCount; i++)
		{
			calc->nextGeneration();
			calc->nextEvolution(i, size);
		}

		cout << "Done in :" << (time(NULL) - start) << " sec." << endl;
	}
	else
	{
		ParallelWorker pw(conf, calc, loader->getData());
		pw.work(size);
	}

	MPI::Finalize();

	delete conf;
	delete loader;

	return EXIT_SUCCESS;
}

